package com.hrbxlh.virtualization.controller;

import com.hrbxlh.virtualization.exception.GlobalException;
import com.hrbxlh.virtualization.result.Result;
import com.hrbxlh.virtualization.result.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * 异常统一处理
 *
 * @author cheer
 */
@ControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<String> handleArgumentException(Exception e) {
        MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
        String message = ex.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Result.error(ResultEnum.BIND_ERROR.fillArgs(message));
    }

    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public Result handleGlobalException(Exception e) {
        logger.error(e.getMessage(), e);
        GlobalException ex = (GlobalException) e;
        if (ex.getResultEnum() != null) {
            return Result.error(ex.getResultEnum());
        }
        return Result.error(ResultEnum.SERVER_ERROR, e.getMessage());

    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return Result.error(ResultEnum.SERVER_ERROR);
    }
}
